// Tooltip.cpp
#include "Tooltip.h"

#include <QGraphicsScene>
#include <QGraphicsSimpleTextItem>
#include "MemCheck.h"

using namespace IDS::IDEAS::OpenGLView::GUIElements;

// ------------------------------------------------------------------------------------------------------
Tooltip::Tooltip()
:	GUIElement(0,0),
	text(""),
	vis(false)
{
    setFlag(QGraphicsItem::ItemIsMovable, false);
    setFlag(QGraphicsItem::ItemIsSelectable, false);
    setFlag(QGraphicsItem::ItemIsFocusable, false);
    setAcceptHoverEvents(false);

	rect = QRect(0,0,0,0);
}

// ------------------------------------------------------------------------------------------------------
Tooltip::~Tooltip()
{ }

//-------------------------------------------------------------------------------------------------
void Tooltip::setText(const QString &t)
{
	text = t;

	QGraphicsSimpleTextItem txt(text);
	rect = txt.boundingRect();
}

//-------------------------------------------------------------------------------------------------
QRectF Tooltip::boundingRect() const
{
	return rect;
}

//-------------------------------------------------------------------------------------------------
void Tooltip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	if( text.length() == 0 )
		return;

	painter->setRenderHint(QPainter::Antialiasing, true);
	painter->setRenderHint(QPainter::TextAntialiasing, true);
	painter->setRenderHint(QPainter::SmoothPixmapTransform, true);

	painter->drawRect(rect);

	QBrush b = painter->brush();
	painter->setBrush( QBrush(QColor(255,255,225), Qt::SolidPattern ) );	

	painter->drawRect(rect);
	painter->setBrush(b);
	painter->drawText(rect, text);

	painter->setRenderHint(QPainter::Antialiasing, false);
	painter->setRenderHint(QPainter::TextAntialiasing, false);
	painter->setRenderHint(QPainter::SmoothPixmapTransform, false);

	GUIElement::paint(painter, option, widget);
}

//-------------------------------------------------------------------------------------------------
QVariant Tooltip::itemChange ( GraphicsItemChange change, const QVariant & value )
{
	if( scene() && (change == ItemPositionChange ||  change == ItemVisibleChange) )
	{
		const int w = scene()->width();
		const int h = scene()->height();

		if( x() < 0 )						setX(0);
		if( y() < 0 )						setY(0);
		if( x() + rect.width()  >= w )	setX( w - rect.width() );
		if( y() + rect.height() >= h )	setY( h - rect.height() );
	}

	return QGraphicsItem::itemChange(change, value);
}